package com.yhsoft.flim.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yhsoft.benefitcard.service.ICardsInfoService;
import com.yhsoft.buyer.service.IBuyerOrderService;
import com.yhsoft.common.response.PageResult;
import com.yhsoft.common.service.TokenService;
import com.yhsoft.common.vo.Result;
import com.yhsoft.flim.controller.request.*;
import com.yhsoft.flim.controller.response.*;
import com.yhsoft.flim.entity.HotMovie;
import com.yhsoft.flim.entity.MoviePlans;
import com.yhsoft.flim.entity.MovieSeat;
import com.yhsoft.flim.service.*;
import com.yhsoft.goods.controller.requset.AllGoodsInVo;
import com.yhsoft.goods.controller.response.AllGoodsOutVo;
import com.yhsoft.flim.controller.response.GetFlimModeInfoOutVo;
import com.yhsoft.goods.entity.CompanyGoods;
import com.yhsoft.goods.service.ICompanyGoodsService;
import com.yhsoft.wxprogram.controller.response.BenefitCardOutVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @author: yyyyyyyh
 * @create: 2023-12-05
 * @Version 1.0
 **/
@Api(tags = {"M-小程序电影模块"})
@RestController
@RequestMapping("/film")
@Slf4j
public class FlimController {
    @Resource
    private ICinemaService iCinemaService;

    @Resource
    private IMoviePlansService iMoviePlansService;

    @Resource
    private IHotMovieService iHotMovieService;

    @Resource
    private ICompanyGoodsService iCompanyGoodsService;

    @Resource
    private IFlimService iFlimService;

    @Resource
    private ICardsInfoService iCardsInfoService;

    @Autowired
    private QRCodeService qrCodeService;

    @Autowired
    private IBuyerOrderService iBuyerOrderService;

    @ApiOperation("渠道商查询电影模块状态及价格")
    @GetMapping("/getFlimModeInfo")
    public Result<GetFlimModeInfoOutVo> getFlimModeInfo() {
        GetFlimModeInfoOutVo outVo = iCompanyGoodsService.getFlimModeInfo();
        return Result.success(outVo);
    }

    @ApiOperation("渠道商商品管理设置电影模块加价")
    @PostMapping("/setFlimAddPrice")
    public Result<?> setFlimAddPrice(@Validated @RequestBody SetFlimAddPriceInVo inVo) {
        LambdaQueryWrapper<CompanyGoods> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CompanyGoods::getCompanyId, TokenService.getUserBytoken().getCompanyId());
        wrapper.eq(CompanyGoods::getGoodsId, 0);
        CompanyGoods companyGoods = iCompanyGoodsService.getOne(wrapper);
        companyGoods.setFlimAddPrice(inVo.getFlimAddPrice());
        companyGoods.setStatusMallUp(inVo.getStatusMallUp());
        iCompanyGoodsService.updateById(companyGoods);

        return Result.success("设置成功！");
    }

    @ApiOperation("判断是否分配电影模块")
    @GetMapping("/canUseFlim")
    public Result<?> canUseFlim() {
        LambdaQueryWrapper<CompanyGoods> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CompanyGoods::getCompanyId, TokenService.getUserBytoken().getCompanyId());
        wrapper.eq(CompanyGoods::getGoodsId, 0);
        wrapper.eq(CompanyGoods::getStatusMallUp,1);
        BenefitCardOutVo cardsInfo = iCardsInfoService.getInUseCard();
        if (cardsInfo == null) {
            return Result.fail("请选择福利卡！");
        }
        String cardType = cardsInfo.getCardType();
        if (iCompanyGoodsService.getBaseMapper().exists(wrapper)) {
            if (cardType.equals("DYQ") && cardsInfo.getIsUsed() == 0) {
                return Result.success("可使用电影模块");
            } else if (cardType.equals("JFK") && iCardsInfoService.getCanPayCards(0).size() > 0) {
                return Result.success("可使用电影模块");
            } else if (cardType.equals("LPK")) {
                return Result.fail("当前福利卡为礼品卡，不可使用电影模块！");
            }
        }
        return Result.fail("未分配电影模块，暂不可使用！");
    }

    @ApiOperation("热映影片列表接口")
    @GetMapping("/getHotMovie")
    public Result<List<HotMovie>> getHotMovie() {
        List<HotMovie> hotMovies = iHotMovieService.getHotMovie("HotMovie");
        if (hotMovies == null) {
            return Result.success("数据为空！");
        }
        return Result.success(hotMovies);
    }

    @ApiOperation("即将上映影片列表接口")
    @GetMapping("/getSoonMovie")
    public Result<List<HotMovie>> getSoonMovie() {
        List<HotMovie> hotMovies = iHotMovieService.getHotMovie("SoonMovie");
        if (hotMovies == null) {
            return Result.success("数据为空！");
        }
        return Result.success(hotMovies);
    }

    @ApiOperation("获取影院列表接口")
    @GetMapping("/getCinema")
    public Result<PageResult<CinemaOutVo>> getCinema(GetCinemaInVo inVo,
                                                     @RequestParam(value = "pageNo") Long pageNo,
                                                     @RequestParam(value = "pageSize") Long pageSize) throws IOException {
        IPage<CinemaOutVo> iPage = iCinemaService.getCinema(inVo, pageNo, pageSize);

        return Result.success(PageResult.valueOf(iPage));
    }

    // 获取场次列表
    @ApiOperation("获取场次列表")
    @PostMapping("/plans")
    public Result<List<MoviePlans>> getMoviePlans(@Valid @RequestBody GetMoviePlansInVo inVo) {
        List<MoviePlans> moviePlans = iMoviePlansService.getMoviePlans(inVo);
        if (moviePlans == null) {
            return Result.success("数据为空！");
        }
        return Result.success(moviePlans);
    }

    //座位图数据接口(实时调用)
    @ApiOperation("座位图数据接口")
    @PostMapping("/seat")
    public Result<List<MovieSeat>> getMovieSeat(@Valid @RequestBody GetMovieSeatInVo inVo) throws IOException {
        List<MovieSeat> moviePlans = iFlimService.getMovieSeat(inVo);
        if (moviePlans == null) {
            return Result.fail("获取座位图失败，该场次已经过期或下线!");
        }
        return Result.success(moviePlans);
    }

    //座位图锁座接口
    @ApiOperation("座位图锁座接口")
    @PostMapping("/lock")
    public Result<MovieSeatLockOutVo> movieSeatLock(@Valid @RequestBody MovieSeatLockInVo inVo) throws IOException {
        MovieSeatLockOutVo outVo = iFlimService.movieSeatLock(inVo);
        if (outVo == null) {
            return Result.fail("锁座失败!");
        } else if (!outVo.isSuccess()) {
            return Result.fail(outVo.getMsg());
        }
        return Result.success(outVo);
    }

    //座位图解锁接口
    @ApiOperation("座位图解锁接口")
    @PostMapping("/unlock")
    public Result<MovieSeatUnlockOutVo> movieSeatUnlock(@Valid @RequestBody MovieSeatUnlockInVo inVo) throws IOException {
        MovieSeatUnlockOutVo outVo = iFlimService.movieSeatUnlock(inVo);
        if (outVo == null) {
            return Result.fail("解锁失败!");
        }
        return Result.success(outVo);
    }

    //支付确认接口（出票接口）
    @ApiOperation("电影票支付接口（旧）")
    @PostMapping("/pay1")
    public Result<FlimPayOutVo> pay(@Valid @RequestBody FlimPayInVo inVo) throws IOException {
        FlimPayOutVo outVo = iFlimService.pay(inVo);
        if (outVo == null) {
            return Result.fail("支付失败!");
        }
        return Result.success(outVo);
    }

    //支付确认接口（出票接口）
    @ApiOperation("电影票支付接口（出票接口）（新）")
    @PostMapping("/pay")
    public Result<FlimPayOutVo> pay_new(@Valid @RequestBody FlimPayInVo inVo) throws IOException {
        FlimPayOutVo outVo = iFlimService.payFlim(inVo.getOrderId());
        if (outVo == null) {
            return Result.fail("支付失败!");
        }
        if (!outVo.isSuccess()) {
            return Result.fail(outVo.getMsg());
        }
        return Result.success(outVo);
    }

    //出票查询
    @ApiOperation("出票查询")
    @GetMapping("/query")
    public Result<QueryOutVo> query(@RequestParam(value = "orderId") String orderId) throws IOException {
        QueryOutVo outVo = iFlimService.query(orderId);
        if (outVo == null) {
            return Result.success("出票中...");
        }
        return Result.success(outVo);
    }

    @ApiOperation("提交订单")
    @PostMapping("/submit")
    public Result<SubmitOutVo> submit(@Valid @RequestBody FlimSubmitInVo inVo) throws IOException {
        SubmitOutVo outVo = iFlimService.submit(inVo);
        if (outVo == null) {
            return Result.fail("解锁失败!");
        }
        return Result.success(outVo);
    }

    @ApiOperation("查询我的电影券福利卡")
    @GetMapping("/getFlimBenefitCard")
    public Result<List<BenefitCardOutVo>> getFlimBenefitCard() {
        List<BenefitCardOutVo> list = iCardsInfoService.getFlimBenefitCard();
        return Result.success(list);
    }

    @ApiOperation("获取二维码（流）")
    @GetMapping("/qrCode")
    public void getQRCode(@RequestParam(value = "ticket") String ticket, HttpServletResponse response) {
        try {
            log.info("过滤前：" + ticket);
            String REGEX = "[^0-9]";
            ticket = Pattern.compile(REGEX).matcher(ticket).replaceAll("").trim();
            log.info("过滤后：" + ticket);
            qrCodeService.createQRCode2Stream(ticket, response);
            log.info("成功生成二维码！");
        } catch (Exception e) {
            log.error("发生错误， 错误信息是：{}！", e.getMessage());
        }
    }

    @ApiOperation("获取二维码（Base64）")
    @GetMapping("/qrCodeBase64")
    public Result<?> getQRCodeBase64(@RequestParam(value = "ticket") String ticket) {
        String ret = "";
        try {
            log.info("过滤前：" + ticket);
            String REGEX = "[^0-9]";
            ticket = Pattern.compile(REGEX).matcher(ticket).replaceAll("").trim();
            log.info("过滤后：" + ticket);
            ret = qrCodeService.createQRCode2Base64(ticket);
            log.info("成功生成二维码！");
        } catch (Exception e) {
            log.error("发生错误， 错误信息是：{}！", e.getMessage());
        }
        return Result.success(ret, "success");
    }

    @ApiOperation("电影票订单查询")
    @GetMapping("/queryDYOrderList")
    public Result<PageResult<DYOrderOutVo>> queryDYOrderList(@RequestParam(value = "pageNo") Long pageNo, @RequestParam(value = "pageSize") Long pageSize) throws IOException {
        IPage<DYOrderOutVo> convert = iBuyerOrderService.queryDYOrderList(pageNo, pageSize);
        return Result.success(PageResult.valueOf(convert));
    }
}
